package com.foreknow.dao.impl;

import com.foreknow.dao.GuestbookDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Gusetbook;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class GuestbookImpl extends BaseDAO implements GuestbookDao {
    @Override
    public boolean addMessage(Gusetbook gusetbook) throws SQLException {
        String sql="insert into guestbook(name,phone,email,title,content,createdtime)values(?,?,?,?,?,?)";
       int x= jdbcTemplate.update(sql,gusetbook.getName(),gusetbook.getPhone(),gusetbook.getEmail(),gusetbook.getTitle(),gusetbook.getContent(),gusetbook.getCreatedtime());
        return x==1;
    }

    @Override
    public List<Object> getQueryAll() throws SQLException {
        String sql="select * from guestbook";
        //这里集成BaseDao所以直接调用方法拿到mapping
        EntityMapping mapping=this.mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        //因为信息是全部信息,所以返回的集合直接return就可以
        List<Object> list = this.jdbcTemplate.query(sql, mapping);

        return list;
    }

    @Override
    public boolean deleteById(Integer id) throws SQLException {
        String sql="delete from guestbook where id=?";
        int update = this.jdbcTemplate.update(sql, id);
        return update==1;
    }

    @Override
    public Gusetbook queryById(Integer id) throws SQLException {
        String sql="select * from guestbook where id=?";
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = this.jdbcTemplate.query(sql, mapping, id);
        if (list.size()>0){
            return (Gusetbook)list.get(0);
        }
       else{
           return null;
        }
    }

    @Override
    public int updateById(int id, Gusetbook gusetbook,Connection conn) throws SQLException {
       PreparedStatement ps= conn.prepareStatement("update guestbook set name=?,phone=?,email=?,title=?,content=?,createdtime=? where id=?");
       ps.setString(1,gusetbook.getName());
       ps.setString(2,gusetbook.getPhone());
       ps.setString(3,gusetbook.getEmail());
       ps.setString(4,gusetbook.getTitle());
       ps.setString(5,gusetbook.getContent());
       ps.setString(6,gusetbook.getCreatedtime());
       ps.setInt(7,id);
        int i = ps.executeUpdate();
        return i;
    }



}
